package com.test.qpbgboot.base.utils;

import com.test.qpbgboot.base.exception.ServiceException;
import com.test.qpbgboot.base.response.ResultStatus;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

@Slf4j
public class JwtTokenUtils {

    private static final String secretKey = "zhSecretKeOfJWT";

    private static Key getKey() {
        return new SecretKeySpec(
                DatatypeConverter.parseBase64Binary(secretKey),
                SignatureAlgorithm.HS256.getJcaName());
    }

public static <T> String createJWT(T data, Integer expiration) {
    // 创建JWT，添加数据声明，设置过期时间和签名算法，并生成密钥
    String jwt = Jwts.builder().claim("data", data)
            .setExpiration(new Date(System.currentTimeMillis() +
                    expiration * 1000))
            .signWith(SignatureAlgorithm.HS256, getKey())
            .compact();

    // 记录生成的JWT
    log.debug("生成jwt:{}", jwt);

    // 返回生成的JWT
    return jwt;
}

    public static <T> T parseJWT(String token, Class<T> tClass) {
        log.debug("解析token token:{},tClass:{}", token, tClass);
        Claims claims = Jwts.parser().setSigningKey(getKey())
                .parseClaimsJws(token).getBody();
        if ( claims.getExpiration().before(new Date()) ) {
            throw new ServiceException(ResultStatus.EXPIRED_TOKEN);
        }
        T obj = claims.get("data", tClass);
        log.debug("解析结果:{}", obj);
        return obj;
    }

}
